package com.leetcode.tree;

import java.util.HashMap;
import java.util.Map;

/**
 * leetcode 105题：先序中序求树
 */
public class Leetcode105 {

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null && inorder == null)
            return null;

        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++ ) {
            map.put(inorder[i], i);
        }

        return buildChildTree(preorder, 0, preorder.length, inorder, 0, inorder.length, map);
    }

    /**
     *
     * @param preorder 先序序列
     * @param pStart 先序起始节点
     * @param pEnd 先序终止节点
     * @param inorder 中序序列
     * @param iStart 中序起始节点
     * @param iEnd 中序终止节点
     * @return 树根节点
     */
    private TreeNode buildChildTree(int[] preorder, int pStart, int pEnd, int[] inorder, int iStart, int iEnd
            ,Map<Integer, Integer> map) {

        if (pStart == pEnd)
            return null;

        TreeNode root = new TreeNode(preorder[pStart]);
        int rootValue = root.val;
        // 找到根节点在中序节点中的位置
        int rootIndex = map.get(rootValue);
        // 左子树的节点个数
        int leftNum = rootIndex - iStart;
        root.left = buildChildTree(preorder, pStart + 1, pStart + leftNum + 1, inorder, iStart, rootIndex,map);
        root.right = buildChildTree(preorder, pStart + leftNum + 1, pEnd, inorder, rootIndex + 1, iEnd,map);
        return root;
    }

}
